<?php

class Articles
{
	private $id = -1; // note id
	
	private $title = null; // Title
	private $link = null; //url
	private $author = null; // Author
	private $datePublished = null;
	private $dateCreated = null;
	private $dateUpdated = null;
	private $body = null; // body
	private $comment = null;
	private $category_id = null; // Category
	private $hash = null;
	private $cited = 0; // used, cited ? (boolean)
	private $dateCited = null; // date used
	
	private $tagSet = null;
	
	public $display = true;
			
	// Constructor
	function __construct($id = -1)
	{
		if($id > 0) $this->id = $id;
	}
	
	##########################
	# Loads notes from the database and returns Note objects
	# Use : $note = Note::load($note_id) // loads 1 note identified by its ID, returns a Note object
	# Use : $notes = Note::load("all") // loads all notes and returns an array of Note objects
	# Param : id, limit, param ('before' or 'after')
	# Returns : object Note (single) or object NoteSet (range of notes or all notes)
	public static function load($id = "all", $limit="none", $param = "none")
	{
		$db = new Database();
		
		// all notes ==> $articlesSet = Articles::load()
		if(!is_numeric($id) or $id == "all")
		{
			$ns = new ArticlesSet();
			$query = $db->select("articles");
			while($data = $db->fetch())
			{
				$ns->append(Articles::load($data['id']));
			}
			return $ns;
		}
		// one note, identified by its id ==> $article = Articles::load(12)
		elseif(is_numeric($id) and $limit == "none")
		{
			$ar['id'] = $id;
		
			$db->select("articles",'*',$ar, '1');
			$data = $db->fetch();
		
			$a = new Articles();
			$a->setId($data['id']);
			$a->setTitle($data['title']);
			$a->setLink($data['link']);
			$a->setAuthor($data['author']);
			$a->setDatePublished($data['datePublished']);
			$a->setDateCreated($data['dateCreated']);
			$a->setDateUpdated($data['dateUpdated']);
			$a->setBody($data['body']);
			$a->setComment($data['comment']);
			$a->setCategoryId($data['category_id']);
			$a->setHash($data['hash']);
			$a->setCited($data['cited']);
			$a->setDateCited($data['dateCited']);
			$a->setTagSet(Tag::load("all",$data['id']));
			return $a;
		}
		// a range of notes (starting from id) ==> $articlesSet = Articles::load(12,24)
		elseif(is_numeric($id) and is_numeric($limit) and $param == "none")
		{
			$ns = new ArticlesSet();
			$query = $db->select("articles", '*', 1, $id.','.$limit);
			while($data = $db->fetch())
			{
				$ns->append(Articles::load($data['id']));
			}
			return $ns;
		}
	}
		
	##########################
	# Creates a NEW note and injects it into the database
	# Use : 1) set the variables with setter methods, 2) call this method
	# Param :
	# Returns :
	public function create()
	{
		$data['id'] = '';
		$data['title'] = $this->getTitle();
		$data['link'] = $this->getLink();
		$data['author'] = $this->getAuthor();
		$data['datePublished'] = $this->getDatePublished();
		$data['dateCreated'] = $this->getDateCreated();
		$data['dateUpdated'] = $this->getDateUpdated();
		$data['body'] = $this->getBody();
		$data['comment'] = $this->getComment();
		$data['category_id'] = $this->getCategoryId();
		$data['hash'] = $this->makeHash();
		$data['cited'] = $this->getCited();
		$data['dateCited'] = $this->getDateCited();
		
		// Charset conversion
		//foreach($data as $k=>$v)
		//	$data[$k] = utf8_decode($v);
		
		$db = new Database();
		
		// Hash control : do not create a note if it already exists !
		$db->query("SELECT * FROM articles WHERE hash='".$data['hash']."'");
		if($db->num_rows() > 0)
			return false;
		
		return $db->insert("articles",$data);
	}
	
	##########################
	# Updates the current note in the database
	# Use : 1) set the variables with setter methods, 2) call this method
	# e.g. $note->save() // saves all fields in $note instance
	# Use : 1) set one variable with its setter, 2) call this method with the name of the field
	# e.g. : $note->save('title') // saves only 'title' field in $note instance
	# Param :
	# Returns :
	public function save($field = "")
	{
		// Save all fields
		if(empty($field))
		{
			//$data['id'] = $this->getId();
			$data['title'] = $this->getTitle();
			$data['link'] = $this->getLink();
			$data['author'] = $this->getAuthor();
			$data['datePublished'] = $this->getDatePublished();
			$data['dateCreated'] = $this->getDateCreated();
			$data['dateUpdated'] = $this->getDateUpdated();
			$data['body'] = $this->getBody();
			$data['comment'] = $this->getComment();
			$data['hash'] = $this->makeHash();
			$data['category_id'] = $this->getCategoryId();
			$data['cited'] = $this->getCited();
			$data['dateCited'] = $this->getDateCited();
			
			$db = new Database();
			return $db->update("articles",$data,"id='".$this->getId()."'");
		}
		// Save one field
		else
		{
			$getField = 'get'.ucfirst($field);
			$val = $this->$getField();
			$data[$field] = $val;
			$data['dateUpdated'] = "now()";
			$db = new Database();
			return $db->update("articles",$data,"id='".$this->getId()."'");
		}
	}
	
	##########################
	# Prints the value of the given variable
	# Param : the name of one of the class variables (e.g. 'title' or 'body')
	# Returns :
	public function show($element)
	{
		$res = "";
		switch($element)
		{
			// Default fields
			case 'id':		$res =  $this->getId(); break;
			case 'title':	$res =  $this->getTitle(); break;
			case 'link':	$res =  $this->getLink(); break;
			case 'author':	$res =  $this->getAuthor(); break;
			case 'datePublished':	$res =  $this->getDatePublished(); break;
			case 'dateCreated':	$res =  $this->getDateCreated(); break;
			case 'dateUpdated':	$res =  $this->getDateUpdated(); break;
			case 'body':	$res =  $this->getBody(); break;
			case 'comment': $res =  $this->getComment(); break;
			case 'hash':	$res =  $this->getHash(); break;
			case 'cited':		$res =  $this->getCited(); break;
			case 'dateCited':		$res =  $this->getDateCited(); break;
			case 'category_id': $res =  $this->getCategoryId(); break;
			case 'category':	$res =  $this->getCategory(); break;
			// Special fields
			case 'tags': $res = $this->getTagSet()->getFormatedList(); if($this->countTags() > 0 ) $res = "{".$res."}"; break;
			// Formated fields
			case 'linked-title': $res =  $this->getLinkedTitle(); break;
			case 'date_published_f': $res = formatDate("d/m/Y",$this->getDatePublished()); break;
			case 'date_published_f2': $res = formatDate("d M Y",$this->getDatePublished()); break;
			default: $res =  ""; break;
		}
		echo utf8_encode($res);
	}
	
	##########################
	# Adds a tag (existing OR new) to the current article
	# Param : name of the tag
	# Returns :
	public function addTag($tag_name)
	{
		$tag = null;
		
		// Does the tag already exist in the Tags table ?
		$tag_exists = Tag::isTag($tag_name);
		// If the tag doesn't already exist, let's create it
		if(!$tag_exists)
		{
			$tag = new Tag(null,$tag_name); // id,tag
			$tag->create();
		}
		// Load the tag
		$tag = Tag::load($tag_name);
		
		// Reload the TagSet of the article
		$this->setTagSet(Tag::load("all",$this->getId()));
				
		// Has the tag already been associated with this article ? If yes, just return false.
		if($this->hasTag($tag->getTag()))
			return false;
			
		// Make the association between the tag and the article in the join table
		$data = array();
		$data['id'] = '';
		$data['tag_id'] = $tag->getId();
		$data['article_id'] = $this->getId();
		$db = new Database();
		$db->insert("tag_join_article",$data);
		
		// Reload the tag set
		$this->setTagSet(Tag::load("all",$this->getId()));
		// ok
		return true;
	}
	
	##########################
	# Adds all the tags of the given TagSet to the current Article
	# Param : TagSet object
	# Returns : array of tags STRING (not objects) added to the article
	public function addTagSet($tagset)
	{
		$res = array();
		$db = new Database();
		// Loop all tags in the set
		foreach($tagset->getTags() as $tag)
		{
			// Add only if not already associated
			if(!$this->hasTag($tag->getTag()))
			{
				// Add the tag-article association in the join table
				$data = array();
				$data['id'] = '';
				$data['tag_id'] = $tag->getId();
				$data['article_id'] = $this->getId();
				$db->insert("tag_join_article",$data);
				// Add in the return-for-display array
				$res[] = $tag->getTag();
			}
		}
		return $res;
	}
	
	##########################
	# Check if this article has been associated with the given tag, id or name
	# Param : **STRING** name of the tag or id (and NOT an instance of Tag class !!!)
	# Returns : true or false
	public function hasTag($tag)
	{
		if(empty($this->tagSet))
			return false;
		elseif($this->getTagSet()->hasTag($tag))
			return true;
		else
			return false;
	}
	
	##########################
	# Return the number of tags associated with this article
	# Param : 
	# Returns : integer
	public function countTags()
	{
		return $this->getTagSet()->count();
	}
	
	##########################
	# Setters
	public function setId($id) { $this->id = $id; }
	public function setTitle($title) { $this->title = $title; }
	public function setLink($url) { $this->link = $url; }
	public function setAuthor($author) { $this->author = $author; }
	public function setDatePublished($d) { if(is_null($d)) $d = date("Y-m-d H:i:s"); $this->datePublished = $d; }
	public function setDateCreated($d) { if(is_null($d)) $d = date("Y-m-d H:i:s"); $this->dateCreated = $d; }
	public function setDateUpdated($d) { if(is_null($d)) $d = date("Y-m-d H:i:s"); $this->dateUpdated = $d; }
	public function setBody($body) { $this->body = $body; }
	public function setComment($com) { $this->comment = $com; }
	public function setCategoryId($id) { $this->category_id = $id; }
	public function setHash($hash) { $this->hash = $hash; }
	public function setCited($u=1) { $this->cited = $u; }
	public function setDateCited($d=null) { if(is_null($d)) $d = date("Y-m-d"); $this->dateCited = $d; }
	public function setTagSet($ts) { $this->tagSet = $ts; }
	
	##########################
	# Getters
	public function getId() { return $this->id; }
	public function getTitle() { return $this->title; }
	public function getLink() { return $this->link; }
	public function getAuthor() { return $this->author; }
	public function getDatePublished() { return $this->datePublished; }
	public function getDateCreated() { if(is_null($this->dateCreated)) $this->dateCreated = date("Y-m-d H:i:s"); return $this->dateCreated; }
	public function getDateUpdated() { if(is_null($this->dateUpdated)) $this->dateUpdated = date("Y-m-d H:i:s"); return $this->dateUpdated; }
	public function getBody() { return $this->body; }
	public function getComment() { return $this->comment; }
	public function getCategoryId() { return $this->category_id; }
	public function getHash() { return $this->hash; }
	public function getCited() { return $this->cited; }
	public function getDateCited() { return $this->dateCited; }
	public function getTagSet() { return $this->tagSet; }
	

	
	public function getCategoryName()
	{
		$cat = $this->getCategory();
		if($cat) 
			$category = $cat->show('category');
		else 
			$category = "";
		return $category;
	}
	
	public function getCategory()
	{
		$cat = Category::load($this->category_id); // return false is category is null
		if($cat)
			return $cat;
	}
	
	public function getLinkedTitle()
	{
		// Open in new window/tab ?
			$prefs = Preferences::loadForUser(Session::getFromSession('uid'));
			if($prefs->getValue('rss_open_link_in_new_page'))
				$lnk = " target=\"_blank\" ";
			else
				$lnk = "";
		// Make link
		return "<a href=\"".$this->getLink()."\"$lnk>".$this->getTitle()."</a>";
	}
	
	##########################
	# Make a unique hash for this note
	public function makeHash()
	{
		$this->hash = sha1($this->title . $this->author . $this->link);
		return $this->hash;
	}
	
}

?>